﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Web.Mvc;
using MvcApplicationBindersSample.Models;

namespace MvcApplicationBindersSample.Controllers {
    public class PeopleController : Controller {

        public ActionResult Index() {
            using (var dc = new SampleEntities()) {

                // No binding or other special logic takes place, so it's easiest just to let the
                // view operate directly against the ORM object.
                Person[] people = dc.People.OrderBy(p => p.LastName).ToArray();
                return View(people);
            }
        }

        [HttpGet]
        public ActionResult Create() {
            return View("CreateEdit");
        }

        [HttpPost]
        public ActionResult Create(CreateEditPersonModel model) {
            if (model != null && ModelState.IsValid) {
                using (var dc = new SampleEntities()) {
                    Person person = new Person();
                    dc.People.AddObject(person);

                    // convert this single CreateEditPersonModel to a Person
                    ModelCopier.CopyModel(model, person);
                    dc.SaveChanges();
                    return RedirectToAction("Index");
                }
            }

            // something went wrong
            return View("CreateEdit", model);
        }

        [HttpGet]
        public ActionResult Edit(int id) {
            using (var dc = new SampleEntities()) {
                Person person = dc.People.Single(p => p.PersonId == id);

                // convert this single Person to a CreateEditPersonModel
                CreateEditPersonModel model = new CreateEditPersonModel();
                ModelCopier.CopyModel(person, model);
                return View("CreateEdit", model);
            }
        }

        [HttpPost]
        public ActionResult Edit(int id, CreateEditPersonModel model) {
            if (model != null && ModelState.IsValid) {
                using (var dc = new SampleEntities()) {
                    Person person = dc.People.Single(p => p.PersonId == id);

                    // copy the incoming CreateEditPersonModel to the original Person
                    ModelCopier.CopyModel(model, person);
                    dc.SaveChanges();
                    return RedirectToAction("Index");
                }
            }

            // validation error
            return View("CreateEdit", model);
        }

    }
}
